package com.gaga.console.core.controller.common;


import com.gaga.common.entity.file.FileDesc;
import com.gaga.common.path.ApiPath;
import com.gaga.common.result.Result;
import com.gaga.console.base.controller.BaseController;
import com.gaga.console.core.service.FileManageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.net.URLDecoder;


/**
 * 认证
 *
 * @author liujia
 * @since 2022-05-19
 */
@Api(tags = "通用功能-文件管理")
@RestController
@RequestMapping(ApiPath.ROOT + "/common/fileManage")
public class UploadController extends BaseController {

    @Autowired
    private FileManageService fileManageService;
    private String fileRootDir = URLDecoder.decode(ResourceUtils.getURL("classpath:").getPath());

    public UploadController() throws FileNotFoundException {
    }

    /**
     * @param file
     * @param fileDesc
     * @param request
     * @return
     */
    @ApiOperation(value = "文件上传", httpMethod = "POST")
    @PostMapping("/upload")
    public Result singleFileUpload(@RequestParam("file") MultipartFile file, FileDesc fileDesc, HttpServletRequest request) {

        fileDesc.setServerPath(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath() + "/");
        fileDesc.setPath(fileRootDir);
        try {
            fileDesc = fileManageService.saveFile(file, fileDesc);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
        return Result.ok(fileDesc);
    }
}
